'use client';

import { useState, useEffect, useRef } from 'react';
import { 
  Box, 
  Container, 
  Typography, 
  Paper, 
  TextField, 
  Button, 
  CircularProgress, 
  Card, 
  CardContent,
  Avatar,
  IconButton,
  Divider,
  Alert,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogContentText,
  DialogActions,
  Stepper,
  Step,
  StepLabel,
  Grid,
  Tooltip,
  Snackbar
} from '@mui/material';
import { useParams, useRouter } from 'next/navigation';
import { useTheme } from '@mui/material/styles';
import Navbar from '@/components/Navbar';
import SendIcon from '@mui/icons-material/Send';
import SmartToyIcon from '@mui/icons-material/SmartToy';
import PersonIcon from '@mui/icons-material/Person';
import ArrowBackIcon from '@mui/icons-material/ArrowBack';
import AutoFixHighIcon from '@mui/icons-material/AutoFixHigh';

// 面试岗位数据
const interviewPositions = {
  'java-backend': {
    title: 'Java 后端开发工程师',
    description: '针对Java后端开发技能的专业面试，涵盖Spring Boot、微服务架构、数据库设计等核心知识点',
    level: '中高级',
    skills: ['Java', 'Spring Boot', 'MySQL', '微服务', '分布式系统']
  },
  'frontend': {
    title: 'Web 前端开发工程师',
    description: '评估前端开发能力，包括React/Vue框架、JavaScript深度理解、性能优化等关键技能',
    level: '中级',
    skills: ['React', 'Vue', 'JavaScript', 'CSS', '前端性能优化']
  },
  'devops': {
    title: 'DevOps/运维工程师',
    description: '检验CI/CD流程设计、容器化部署、监控告警体系搭建等运维核心能力',
    level: '高级',
    skills: ['Docker', 'Kubernetes', 'CI/CD', 'Linux', '自动化运维']
  },
  'python-backend': {
    title: 'Python 后端开发工程师',
    description: '专注于Python开发技能评估，包括Django/Flask框架应用、数据处理和API设计',
    level: '中级',
    skills: ['Python', 'Django', 'Flask', 'API开发', '数据处理']
  },
  'security': {
    title: '网络安全工程师',
    description: '全面评估安全漏洞识别、渗透测试、安全防护方案设计等网络安全核心能力',
    level: '资深',
    skills: ['Web安全', '渗透测试', '安全审计', '加密技术', '网络安全架构']
  },
  'mobile': {
    title: '移动端开发工程师',
    description: '针对Android/iOS原生开发或跨平台开发能力的综合评估，包含性能优化与用户体验',
    level: '中高级',
    skills: ['Android', 'iOS', 'React Native', 'Flutter', '移动端性能优化']
  }
};

// 定义消息类型
type Message = {
  id: number;
  content: string;
  role: 'user' | 'assistant';
  timestamp: Date;
};

// 用户信息类型
type UserInfo = {
  name: string;
  education: string;
  years: string;
  skills: string[];
  selfIntro: string;
};

export default function Interview() {
  const router = useRouter();
  const theme = useTheme();
  const { id } = useParams();
  const positionId = Array.isArray(id) ? id[0] : id;
  const position = interviewPositions[positionId as keyof typeof interviewPositions];
  
  const [step, setStep] = useState(0);
  const [userInfo, setUserInfo] = useState<UserInfo>({
    name: '',
    education: '',
    years: '',
    skills: [],
    selfIntro: ''
  });
  
  const [messages, setMessages] = useState<Message[]>([]);
  const [inputMessage, setInputMessage] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [interviewEnded, setInterviewEnded] = useState(false);
  const [feedback, setFeedback] = useState('');
  const [openDialog, setOpenDialog] = useState(false);
  const [snackbarMessage, setSnackbarMessage] = useState('');
  const [snackbarOpen, setSnackbarOpen] = useState(false);

  const messagesEndRef = useRef<HTMLDivElement>(null);
  
  // 当消息更新时自动滚动到底部
  useEffect(() => {
    if (messagesEndRef.current) {
      messagesEndRef.current.scrollIntoView({ behavior: 'smooth' });
    }
  }, [messages]);
  
  // 初始化面试，发送第一条消息
  const startInterview = async () => {
    setStep(1);
    
    // 初始问候消息
    const initialMessage = {
      id: 1,
      content: `你好，${userInfo.name}！我是你今天的${position.title}面试官。我看了一下你的简历，你${userInfo.years}年${position.skills.join('、')}相关经验，毕业于${userInfo.education}。让我们开始今天的面试，请先简单介绍一下你自己和你的技术背景。`,
      role: 'assistant' as const,
      timestamp: new Date()
    };
    
    setMessages([initialMessage]);
  };
  
  // 处理用户消息提交
  const handleSendMessage = async () => {
    if (!inputMessage.trim()) return;
    
    const newUserMessage = {
      id: messages.length + 1,
      content: inputMessage,
      role: 'user' as const,
      timestamp: new Date()
    };
    
    setMessages(prev => [...prev, newUserMessage]);
    setInputMessage('');
    setIsLoading(true);
    
    try {
      // 调用 API 获取 AI 响应
      const response = await fetch('/api/job-assistant/interview', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          position: positionId,
          userInfo,
          messages: [...messages, newUserMessage],
        }),
      });
      
      const data = await response.json();
      
      // 如果面试结束，显示反馈
      if (data.isInterviewEnded) {
        setInterviewEnded(true);
        setFeedback(data.feedback || '');
      }
      
      const newAssistantMessage = {
        id: messages.length + 2,
        content: data.response,
        role: 'assistant' as const,
        timestamp: new Date()
      };
      
      setMessages(prev => [...prev, newAssistantMessage]);
    } catch (error) {
      console.error('面试处理错误:', error);
      // 显示错误信息
      setMessages(prev => [...prev, {
        id: messages.length + 2,
        content: '抱歉，面试过程中遇到了技术问题。请稍后再试。',
        role: 'assistant' as const,
        timestamp: new Date()
      }]);
    } finally {
      setIsLoading(false);
    }
  };
  
  // 结束面试
  const endInterview = () => {
    setOpenDialog(true);
  };

  // 确认结束面试
  const confirmEndInterview = async () => {
    setOpenDialog(false);
    setIsLoading(true);
    
    try {
      // 调用 API 获取面试总结和反馈
      const response = await fetch('/api/job-assistant/interview/feedback', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          position: positionId,
          userInfo,
          messages,
        }),
      });
      
      const data = await response.json();
      setFeedback(data.feedback);
      setInterviewEnded(true);
    } catch (error) {
      console.error('获取面试反馈错误:', error);
      setFeedback('由于技术原因，无法生成完整的面试反馈。');
      setInterviewEnded(true);
    } finally {
      setIsLoading(false);
    }
  };
  
  // 自动填充用户信息
  const autoFillUserInfo = async () => {
    try {
      const token = localStorage.getItem('token');
      
      if (!token) {
        setSnackbarMessage('请先登录后使用此功能');
        setSnackbarOpen(true);
        return;
      }
      
      // 显示加载状态
      setIsLoading(true);
      
      // 调用API获取用户信息
      const response = await fetch('/api/user/profile', {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      });
      
      if (!response.ok) {
        const error = await response.json();
        throw new Error(error.error || '获取用户信息失败');
      }
      
      // 解析返回的用户信息
      const userData = await response.json();
      
      // 更新表单
      setUserInfo({
        name: userData.name || '',
        education: userData.education || '',
        years: userData.years || '',
        skills: userData.skills || [],
        selfIntro: userData.selfIntro || ''
      });
      
      setSnackbarMessage('个人信息已自动填充，您可以继续编辑');
      setSnackbarOpen(true);
    } catch (error) {
      console.error('自动填充用户信息失败:', error);
      setSnackbarMessage('获取个人信息失败: ' + (error instanceof Error ? error.message : '未知错误'));
      setSnackbarOpen(true);
    } finally {
      setIsLoading(false);
    }
  };
  
  // 关闭提示框
  const handleCloseSnackbar = () => {
    setSnackbarOpen(false);
  };
  
  // 渲染用户信息表单
  const renderUserInfoForm = () => (
    <Card sx={{ maxWidth: 800, mx: 'auto', mt: 4, p: 3 }}>
      <CardContent>
        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
          <Typography variant="h5" gutterBottom sx={{ mb: 0 }}>
            请填写您的基本信息
          </Typography>
          
          <Tooltip title="一键填写个人信息">
            <Button
              variant="outlined"
              startIcon={<AutoFixHighIcon />}
              onClick={autoFillUserInfo}
              disabled={isLoading}
            >
              一键填写
            </Button>
          </Tooltip>
        </Box>
        
        <Grid container spacing={3}>
          <Grid item xs={12} md={6}>
            <TextField
              label="姓名"
              fullWidth
              required
              value={userInfo.name}
              onChange={(e) => setUserInfo({...userInfo, name: e.target.value})}
            />
          </Grid>
          <Grid item xs={12} md={6}>
            <TextField
              label="最高学历"
              fullWidth
              required
              value={userInfo.education}
              onChange={(e) => setUserInfo({...userInfo, education: e.target.value})}
            />
          </Grid>
          <Grid item xs={12} md={6}>
            <TextField
              label="工作经验年限"
              fullWidth
              required
              value={userInfo.years}
              onChange={(e) => setUserInfo({...userInfo, years: e.target.value})}
            />
          </Grid>
          <Grid item xs={12} md={6}>
            <TextField
              label="技能（用逗号分隔）"
              fullWidth
              required
              value={userInfo.skills.join(', ')}
              onChange={(e) => setUserInfo({...userInfo, skills: e.target.value.split(',').map(skill => skill.trim())})}
            />
          </Grid>
          <Grid item xs={12}>
            <TextField
              label="个人简介（包括项目经验等）"
              fullWidth
              required
              multiline
              rows={4}
              value={userInfo.selfIntro}
              onChange={(e) => setUserInfo({...userInfo, selfIntro: e.target.value})}
            />
          </Grid>
        </Grid>
        
        <Box sx={{ display: 'flex', justifyContent: 'center', mt: 4 }}>
          <Button 
            variant="contained" 
            size="large" 
            onClick={startInterview}
            disabled={!userInfo.name || !userInfo.education || !userInfo.years || !userInfo.selfIntro || isLoading}
          >
            {isLoading ? <CircularProgress size={24} /> : '开始面试'}
          </Button>
        </Box>
      </CardContent>
    </Card>
  );
  
  // 渲染聊天消息
  const renderMessage = (message: Message) => {
    const isAI = message.role === 'assistant';
    
    return (
      <Box
        key={message.id}
        sx={{
          display: 'flex',
          justifyContent: isAI ? 'flex-start' : 'flex-end',
          mb: 2,
        }}
      >
        <Box
          sx={{
            display: 'flex',
            maxWidth: '75%',
          }}
        >
          {isAI && (
            <Avatar 
              sx={{ 
                bgcolor: theme.palette.primary.main,
                width: 40,
                height: 40, 
                mr: 1 
              }}
            >
              <SmartToyIcon />
            </Avatar>
          )}
          
          <Paper
            elevation={1}
            sx={{
              p: 2,
              borderRadius: 2,
              bgcolor: isAI ? theme.palette.background.paper : theme.palette.primary.main,
              color: isAI ? theme.palette.text.primary : '#fff',
            }}
          >
            <Typography variant="body1" sx={{ whiteSpace: 'pre-wrap' }}>
              {message.content}
            </Typography>
            <Typography variant="caption" sx={{ display: 'block', mt: 1, opacity: 0.7, textAlign: 'right' }}>
              {new Date(message.timestamp).toLocaleTimeString()}
            </Typography>
          </Paper>
          
          {!isAI && (
            <Avatar 
              sx={{ 
                bgcolor: theme.palette.secondary.main,
                width: 40,
                height: 40,
                ml: 1 
              }}
            >
              <PersonIcon />
            </Avatar>
          )}
        </Box>
      </Box>
    );
  };
  
  // 渲染面试聊天界面
  const renderInterviewChat = () => (
    <Box sx={{ maxWidth: 900, mx: 'auto', mt: 2 }}>
      <Paper 
        elevation={3} 
        sx={{ 
          height: '70vh', 
          display: 'flex',
          flexDirection: 'column',
          overflow: 'hidden',
          borderRadius: 2
        }}
      >
        {/* 聊天头部 */}
        <Box sx={{ 
          p: 2, 
          bgcolor: theme.palette.primary.main, 
          color: '#fff',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between'
        }}>
          <Box sx={{ display: 'flex', alignItems: 'center' }}>
            <Avatar sx={{ bgcolor: '#fff', color: theme.palette.primary.main }}>
              <SmartToyIcon />
            </Avatar>
            <Box sx={{ ml: 2 }}>
              <Typography variant="h6">
                {position.title}面试
              </Typography>
              <Typography variant="body2">
                级别: {position.level}
              </Typography>
            </Box>
          </Box>
          
          <Button 
            variant="outlined" 
            color="inherit" 
            size="small"
            onClick={endInterview}
          >
            结束面试
          </Button>
        </Box>
        
        <Divider />
        
        {/* 消息区域 */}
        <Box sx={{ 
          flexGrow: 1, 
          p: 2, 
          overflow: 'auto',
          bgcolor: theme.palette.background.default 
        }}>
          {messages.map(renderMessage)}
          {isLoading && (
            <Box sx={{ display: 'flex', justifyContent: 'flex-start', mb: 2 }}>
              <Box sx={{ display: 'flex' }}>
                <Avatar sx={{ bgcolor: theme.palette.primary.main, mr: 1 }}>
                  <SmartToyIcon />
                </Avatar>
                <Paper
                  elevation={1}
                  sx={{
                    p: 2,
                    borderRadius: 2,
                    display: 'flex',
                    alignItems: 'center',
                  }}
                >
                  <CircularProgress size={20} sx={{ mr: 2 }} />
                  <Typography>正在思考回答...</Typography>
                </Paper>
              </Box>
            </Box>
          )}
          <div ref={messagesEndRef} />
        </Box>
        
        <Divider />
        
        {/* 输入区域 */}
        <Box sx={{ 
          p: 2, 
          bgcolor: theme.palette.background.paper,
          display: 'flex'
        }}>
          <TextField
            fullWidth
            placeholder="输入您的回答..."
            variant="outlined"
            multiline
            maxRows={4}
            value={inputMessage}
            onChange={(e) => setInputMessage(e.target.value)}
            disabled={isLoading || interviewEnded}
            onKeyPress={(e) => {
              if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                handleSendMessage();
              }
            }}
          />
          <IconButton 
            color="primary" 
            onClick={handleSendMessage}
            disabled={!inputMessage.trim() || isLoading || interviewEnded}
            sx={{ ml: 1 }}
          >
            <SendIcon />
          </IconButton>
        </Box>
      </Paper>
    </Box>
  );
  
  // 渲染面试结果和反馈
  const renderInterviewFeedback = () => (
    <Box sx={{ maxWidth: 800, mx: 'auto', mt: 4 }}>
      <Paper elevation={3} sx={{ p: 3, borderRadius: 2 }}>
        <Box sx={{ display: 'flex', alignItems: 'center', mb: 3 }}>
          <Avatar sx={{ bgcolor: theme.palette.primary.main, mr: 2 }}>
            <SmartToyIcon />
          </Avatar>
          <Typography variant="h5">
            面试评估与反馈
          </Typography>
        </Box>
        
        <Divider sx={{ mb: 3 }} />
        
        <Typography variant="body1" paragraph sx={{ whiteSpace: 'pre-wrap' }}>
          {feedback || '面试评估生成中...'}
        </Typography>
        
        <Box sx={{ display: 'flex', justifyContent: 'center', mt: 4 }}>
          <Button 
            variant="outlined" 
            startIcon={<ArrowBackIcon />} 
            onClick={() => router.push('/job-assistant/interviews')}
          >
            返回岗位选择
          </Button>
        </Box>
      </Paper>
    </Box>
  );
  
  // 确认结束面试对话框
  const renderEndInterviewDialog = () => (
    <Dialog
      open={openDialog}
      onClose={() => setOpenDialog(false)}
    >
      <DialogTitle>确认结束面试</DialogTitle>
      <DialogContent>
        <DialogContentText>
          您确定要结束当前面试吗？系统将生成本次面试的评估结果和反馈。
        </DialogContentText>
      </DialogContent>
      <DialogActions>
        <Button onClick={() => setOpenDialog(false)}>取消</Button>
        <Button onClick={confirmEndInterview} variant="contained">
          确认结束
        </Button>
      </DialogActions>
    </Dialog>
  );

  return (
    <Container maxWidth="lg" sx={{ mb: 6 }}>
      {!position && (
        <Alert severity="error" sx={{ mt: 4 }}>
          未找到该面试岗位，请返回选择其他岗位。
          <Button 
            color="inherit" 
            size="small" 
            onClick={() => router.push('/job-assistant/interviews')}
          >
            返回选择
          </Button>
        </Alert>
      )}
      
      {position && (
        <>
          <Box sx={{ my: 4 }}>
            <Stepper activeStep={step} alternativeLabel>
              <Step>
                <StepLabel>填写基本信息</StepLabel>
              </Step>
              <Step>
                <StepLabel>进行面试</StepLabel>
              </Step>
              <Step>
                <StepLabel>面试反馈</StepLabel>
              </Step>
            </Stepper>
          </Box>
          
          {step === 0 && renderUserInfoForm()}
          {step === 1 && !interviewEnded && renderInterviewChat()}
          {interviewEnded && renderInterviewFeedback()}
          {renderEndInterviewDialog()}
        </>
      )}
      
      {/* 添加提示框 */}
      <Snackbar
        open={snackbarOpen}
        autoHideDuration={6000}
        onClose={handleCloseSnackbar}
        message={snackbarMessage}
      />
    </Container>
  );
} 